package com.philip.demo;

import org.bytedeco.javacv.*;
import org.bytedeco.opencv.opencv_core.Mat;
import org.bytedeco.opencv.opencv_core.Rect;

import javax.swing.*;

import java.io.IOException;

import static org.bytedeco.opencv.global.opencv_core.CV_8UC1;
import static org.bytedeco.opencv.global.opencv_imgproc.CV_BGR2GRAY;
import static org.bytedeco.opencv.global.opencv_imgproc.cvtColor;

/**
 * 执行器
 */
public class P_Executor {

    private P_FaceDetect faceDetect;
    private P_FaceRecognizer faceRecognizer;

    public P_Executor() throws IOException {
        String trainingDir = "D:\\test\\capture\\";
        faceDetect = new P_FaceDetect();
        faceRecognizer = new P_FaceRecognizer(trainingDir);
    }


    public void run() throws Exception {
        // The available FrameGrabber classes include OpenCVFrameGrabber (opencv_videoio),
        // DC1394FrameGrabber, FlyCapture2FrameGrabber, OpenKinectFrameGrabber, OpenKinect2FrameGrabber,
        // RealSenseFrameGrabber, RealSense2FrameGrabber, PS3EyeFrameGrabber, VideoInputFrameGrabber, and FFmpegFrameGrabber.
//        FrameGrabber grabber = FrameGrabber.createDefault(0);
        OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(0);
        grabber.start();
        // CanvasFrame, FrameGrabber, and FrameRecorder use Frame objects to communicate image data.
        // We need a FrameConverter to interface with other APIs (Android, Java 2D, JavaFX, Tesseract, OpenCV, etc).
        OpenCVFrameConverter.ToMat converter = new OpenCVFrameConverter.ToMat();
        CanvasFrame frame = new CanvasFrame("摄像头",CanvasFrame.getDefaultGamma()/grabber.getGamma());// 新建一个窗口
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setAlwaysOnTop(true);
        Frame videoFrame = null;
        Mat grabbedImage = converter.convert(grabber.grab());
        int height = grabbedImage.rows();
        int width = grabbedImage.cols();
        Mat grayImage = new Mat(height, width, CV_8UC1);
        while (frame.isVisible() && (grabbedImage = converter.convert(grabber.grab())) != null) {
           cvtColor(grabbedImage, grayImage, CV_BGR2GRAY);
            //使用灰度图进行進行檢測提高準確率
           Rect[] rects=faceDetect.detectFace(grayImage, grabbedImage);

           //進行人臉識別
            for (Rect faceRect: rects) {
                int predictedLabel=faceRecognizer.recognize(grayImage,faceRect);
                if (predictedLabel != -1) {
                    faceRecognizer.markFace(grabbedImage,predictedLabel,faceRect);
                }
            }

           videoFrame = converter.convert(grabbedImage);
           frame.showImage(videoFrame);
        }
        frame.dispose();
        grabber.stop();
    }
}
